package com.wxy.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wxy.entity.Userinfor;
import com.wxy.entity.Users;
import com.wxy.mapper.UserinforMapper;
import com.wxy.mapper.UsersMapper;
import com.wxy.util.jwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.Date;


/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wxy
 * @since 2022-01-12
 */
@RestController
@RequestMapping("/users")
public class UsersController {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserinforMapper userInforMapper;
    //用户登录
    @PostMapping("/login")
    public Users login(
            @RequestBody Users users
            ){
        //查询数据
        QueryWrapper<Users> qw = new QueryWrapper<>();
        qw.eq("userId",users.getUserId());
        qw.eq("passWord",users.getPassWord());
        Users getUser = usersMapper.selectOne(qw);
        if(getUser==null){
            return null;
        }else{
            //登录成功添加token--Jwt
            users.setToken(jwtUtil.createToken());
            return users;
        }
    }
//    用户注册
    @PostMapping("/register")
    public Users register(@RequestBody Users users){
        //查找账户是否已经添加
        QueryWrapper<Users> qw = new QueryWrapper<>();
        qw.eq("userId",users.getUserId());
        Users getUser = usersMapper.selectOne(qw);
        if(getUser==null){
            usersMapper.insert(users);
            Userinfor userinfor = new Userinfor();
            userinfor.setUserId(users.getUserId());
            userinfor.setTell(users.getTel());
            userinfor.setRegisterTime(LocalDateTime.now());
            userInforMapper.insert(userinfor);
            users.setToken(jwtUtil.createToken());
            return users;
        }else{
            return null;
        }
    }

    //检验登录状态
    @GetMapping("/checkToken")
    public boolean checkToken(HttpServletRequest request){
        String token = request.getHeader("token");
        return  jwtUtil.checkToken(token);

    }

}

